#include <sys/types.h>
#include <sys/stat.h>
#include <rclcpp/rclcpp.hpp>
#include <dirent.h>
#include <string>
#include <vector>
#include <memory>

#include "agv_srvs/srv/log_transform.hpp"

using namespace std;
using std::placeholders::_1;
using std::placeholders::_2;

class LogFileConfigNode : public rclcpp::Node
{
public:
    LogFileConfigNode() : Node("log_file_config")
    {
        // 获取home目录路径
        string home_path = getenv("HOME");
        
        // 声明并获取参数
        this->declare_parameter<string>("log_path", "/record");
        string log_path = this->get_parameter("log_path").as_string();
        
        log_file_path_ = home_path + log_path;
        RCLCPP_INFO(this->get_logger(), "log_file: %s", log_file_path_.c_str());
        
        // 创建服务
        service_ = this->create_service<agv_srvs::srv::LogTransform>(
            "log_config",
            std::bind(&LogFileConfigNode::log_config_callback, this, _1, _2));
            
        RCLCPP_INFO(this->get_logger(), "log_config service is start....");
    }

private:
    void log_config_callback(
        const std::shared_ptr<agv_srvs::srv::LogTransform::Request> request,
        std::shared_ptr<agv_srvs::srv::LogTransform::Response> response)
    {
        const char* log_path = log_file_path_.c_str();
        DIR* d = NULL;
        struct dirent* file = new dirent();
        RCLCPP_INFO(this->get_logger(), "req: %d", request->log_status);
        
        if(request->log_status != 0) {
            if(!(d = opendir(log_path))){
                RCLCPP_ERROR(this->get_logger(), "path %s is error", log_path);
                return;
            };
            RCLCPP_INFO(this->get_logger(), "path %s is open", log_path);
            
            string file_name_str = "";
            int count = 0;
            
            while((file = readdir(d)) != NULL) {
                if(strncmp(file->d_name, ".", 1) == 0)   //跳过隐藏文件
                    continue;
                    
                string file_zip;
                if((file_zip = file->d_name).find("zip") != string::npos){
                    file_name_str += file->d_name;
                    file_name_str += "@";
                };
            };
            response->log_filename = file_name_str;
        };
        
        if(d) closedir(d);
        delete file;
    }
    
    rclcpp::Service<agv_srvs::srv::LogTransform>::SharedPtr service_;
    std::string log_file_path_;
};

int main(int argc, char *argv[]){
    setlocale(LC_ALL,"");
    rclcpp::init(argc, argv);
    auto node = std::make_shared<LogFileConfigNode>();
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}